package org.jeecg.modules.hc.service.impl;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.binarywang.spring.starter.wxjava.pay.properties.WxPayProperties;
import com.github.binarywang.wxpay.bean.request.WxPayUnifiedOrderV3Request;
import com.github.binarywang.wxpay.bean.result.WxPayOrderQueryV3Result;
import com.github.binarywang.wxpay.bean.result.WxPayUnifiedOrderV3Result;
import com.github.binarywang.wxpay.bean.result.enums.TradeTypeEnum;
import com.github.binarywang.wxpay.exception.WxPayException;
import com.github.binarywang.wxpay.service.WxPayService;
import com.wechat.pay.java.core.Config;
import com.wechat.pay.java.core.RSAAutoCertificateConfig;
import com.wechat.pay.java.service.payments.model.Transaction;
import com.wechat.pay.java.service.payments.nativepay.NativePayService;
import com.wechat.pay.java.service.payments.nativepay.model.Amount;
import com.wechat.pay.java.service.payments.nativepay.model.PrepayRequest;
import com.wechat.pay.java.service.payments.nativepay.model.PrepayResponse;
import com.wechat.pay.java.service.payments.nativepay.model.QueryOrderByOutTradeNoRequest;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.util.RandomUtils;
import org.apache.commons.lang3.StringUtils;
import org.hibernate.validator.internal.util.stereotypes.Lazy;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.util.IpUtils;
import org.jeecg.common.util.SpringContextUtils;
import org.jeecg.modules.hc.entity.HcOrder;
import org.jeecg.modules.hc.entity.HcWxPay;
import org.jeecg.modules.hc.enums.HcPaymentMethodEnum;
import org.jeecg.modules.hc.enums.HcWxPayStateEnum;
import org.jeecg.modules.hc.mapper.HcWxPayMapper;
import org.jeecg.modules.hc.pcWxPay.config.WeChatConfig;
import org.jeecg.modules.hc.service.IHcOrderService;
import org.jeecg.modules.hc.service.IHcWxPayService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 * @Description: 微信支付
 * @Author: jeecg-boot
 * @Date: 2023-01-07
 * @Version: V1.0
 */
@Slf4j
@Service
public class HcWxPayServiceImpl extends ServiceImpl<HcWxPayMapper, HcWxPay> implements IHcWxPayService {
    @Autowired
    private WxPayService payService;

    @Value("${wx.pay.privateKeyPath}")
    private String privateKeyPath ;

    public HcWxPay pay(String type, String userId, String openId, String description, BigDecimal total) throws WxPayException {
        String outTradeNo = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + RandomUtils.getRandomStr();
        String notifyUrl = "https://btprint.yongshantuan.cn/jeecg-boot/hc/hcWxPay/notify";
        String currency = "CNY";

        type = "jsapi";
        openId = "oP3a362aeLUnznyb_g6-qm38QQmM"; // 请求参数中的 payer.openid
        description= "ppm的红包";
        total = new BigDecimal(0.01);
        WxPayUnifiedOrderV3Request request = new WxPayUnifiedOrderV3Request();
        request.setAppid("wx452cd162d2928e07"); // jx app id
        request.setMchid("1659232319"); // jx merchant id
        request.setDescription(description);
        request.setOutTradeNo(outTradeNo);
        request.setNotifyUrl(notifyUrl);

        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.MINUTE, 15);
        request.setTimeExpire(DateUtil.format(instance.getTime(), "yyyy-MM-dd'T'HH:mm:ssXXX"));

        //构建金额信息
        WxPayUnifiedOrderV3Request.Amount amount = new WxPayUnifiedOrderV3Request.Amount();
        //设置币种信息
        amount.setCurrency(currency);
        //设置金额
        int totalInt = total.multiply(new BigDecimal("100")).intValue();

        amount.setTotal(totalInt);

        request.setAmount(amount);

        HcWxPay wxPay = new HcWxPay().setUserId(userId).setDescription(description).setOutTradeNo(outTradeNo).setNotifyUrl(notifyUrl)
                .setAmountCurrency(currency).setAmountTotal(totalInt);

        if ("jsapi".equals(type)) {
            request.setPayer(new WxPayUnifiedOrderV3Request.Payer().setOpenid(openId));
            WxPayUnifiedOrderV3Result.JsapiResult jsapiResult = this.payService.createOrderV3(TradeTypeEnum.JSAPI, request);
            log.error("prepay: {}", jsapiResult);
            wxPay.setAppid(request.getAppid()).setMchid(request.getMchid()).setTimeStamp(jsapiResult.getTimeStamp()).setNonceStr(jsapiResult.getNonceStr())
                    .setPackageValue(jsapiResult.getPackageValue()).setSignType(jsapiResult.getSignType()).setPaySign(jsapiResult.getPaySign());
        } else {
            //获取request
            HttpServletRequest servletRequest = SpringContextUtils.getHttpServletRequest();
            //获取IP地址
            String ipAddr = IpUtils.getIpAddr(servletRequest);
            request.setSceneInfo(new WxPayUnifiedOrderV3Request.SceneInfo().setPayerClientIp(ipAddr)
                    .setH5Info(new WxPayUnifiedOrderV3Request.H5Info().setType("Wap"))
            );

            String h5Url = this.payService.createOrderV3(TradeTypeEnum.H5, request);
            wxPay.setAppid(request.getAppid()).setMchid(request.getMchid()).setH5Url(h5Url);
        }

//        this.save(wxPay);
        return wxPay;
    }

    public HcWxPay queryPay(String payId) {
        HcWxPay wxPay = this.getById(payId);

        if (wxPay == null) {
            throw new JeecgBootException("订单号不存在");
        }

        WxPayOrderQueryV3Result wxPayOrderQueryV3Result = null;
        try {
            wxPayOrderQueryV3Result = this.payService.queryOrderV3(null, wxPay.getOutTradeNo());
        } catch (WxPayException e) {
            throw new RuntimeException(e);
        }
        System.out.println(wxPayOrderQueryV3Result);

        HcWxPay update = new HcWxPay().setId(wxPay.getId()).setOutTradeNo(wxPay.getOutTradeNo()).setTradeState(wxPayOrderQueryV3Result.getTradeState())
                .setTradeStateDesc(wxPayOrderQueryV3Result.getTradeStateDesc()).setUpdateTime(new Date());

        if (StringUtils.isNotBlank(wxPayOrderQueryV3Result.getSuccessTime())) {
            update.setSuccessTime(DateUtil.parse(wxPayOrderQueryV3Result.getSuccessTime(), "yyyy-MM-dd'T'HH:mm:ssXXX"));
        }

        this.updateById(update);

        update.setAmountTotal(wxPay.getAmountTotal());
        return update;
    }

//    @Override
//    public HcWxPay preNativePay(String userId, String des, BigDecimal total) {
//        String outTradeNo = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + RandomUtils.getRandomStr();
//        String currency = "CNY";
//        // 一个商户号只能初始化一个配置，否则会因为重复的下载任务报错
//        Config config =
//                new RSAAutoCertificateConfig.Builder()
//                        .merchantId(WeChatConfig.merchantId)
//                        .privateKeyFromPath(privateKeyPath)
//                        .merchantSerialNumber(WeChatConfig.merchantSerialNumber)
//                        .apiV3Key(WeChatConfig.apiV3Key)
//                        .build();
//        // 构建service
//        NativePayService service = new NativePayService.Builder().config(config).build();
//
//        //设置金额
//        int totalInt = total.multiply(new BigDecimal("100")).intValue();
////        int totalInt = 1;//测试下单
//        // request.setXxx(val)设置所需参数，具体参数可见Request定义
//        PrepayRequest request = new PrepayRequest();
//        Amount amount = new Amount();
//        amount.setTotal(totalInt);
//        amount.setCurrency(currency);
//        request.setAmount(amount);
//        request.setAppid(WeChatConfig.appId);
//        request.setMchid(WeChatConfig.merchantId);
//        request.setDescription(des);
////        request.setNotifyUrl(WeChatConfig.notifyUrl);
//        request.setOutTradeNo(outTradeNo);
//        // 调用下单方法，得到应答
//        PrepayResponse response = service.prepay(request);
//        // 使用微信扫描 code_url 对应的二维码，即可Native支付
//        if (null == response){
//            throw new JeecgBootException("获取二维码出错");
//        }
//        String codeUrl = response.getCodeUrl();
//        //回调根据单号查询订单状态
//        HcWxPay wxPay = new HcWxPay().setUserId(userId).setDescription(des).setOutTradeNo(outTradeNo).setNotifyUrl("").setAppid(WeChatConfig.appId).setMchid(WeChatConfig.merchantId)
//                .setAmountCurrency(currency).setAmountTotal(totalInt).setQrCode(codeUrl);
//        this.save(wxPay);
//        return wxPay;
//    }


}
